<template>
  <div class="chat-page">
    <div class="chat-container">
      <div class="chat-header">
        <div class="header-title">AI 助手</div>
        <div class="header-subtitle">智能对话</div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <div 
            :class="['message-avatar', message.role === 'user' ? 'user-avatar' : 'ai-avatar']"
          >
            {{ message.role === 'user' ? '👤' : '🤖' }}
          </div>
          <div class="message-content">
            {{ message.content }}
            <span v-if="message.role === 'ai' && message.isActive" class="cursor">|</span>
          </div>
        </div>
      </div>
      
      <div class="chat-input-container">
        <div class="chat-input">
          <input 
            v-model="userInput" 
            @keyup.enter="sendMessage" 
            placeholder="输入您的消息..."
          />
          <button @click="sendMessage" class="send-button">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
              <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, onUnmounted } from 'vue'

const messages = reactive([
  { role: 'ai', content: '你好！我是AI助手，很高兴与您交谈。', isActive: false }
])

const userInput = ref('')
const messagesContainer = ref(null)
const socket = ref(null)

// 初始化WebSocket连接
const initSocket = () => {
  
  socket.value = new WebSocket('http://localhost:3300/test')

  socket.value.onopen = () => {
    console.log('WebSocket连接已建立')
  }

  socket.value.onmessage = (event) => {
    const data = JSON.parse(event.data)
    
    // 查找当前活跃的AI消息
    const activeAIMessageIndex = messages.findIndex(item => item.role === 'ai' && item.isActive === true)

    // 处理接收到的消息
    if (!data.isEnd) {
      if (activeAIMessageIndex === -1) {
        // 如果没有活跃的AI消息，创建新消息
        messages.push({
          role: 'ai',
          content: data.data, // 直接使用第一个字符
          isActive: true
        })
      } else {
        // 如果有活跃的AI消息，追加内容
        messages[activeAIMessageIndex].content += data.data
      }
    } else {
      // 消息结束，标记为非活跃
      if (activeAIMessageIndex !== -1) {
        messages[activeAIMessageIndex].isActive = false
      }
    }

    // 自动滚动到底部
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    })
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }

  socket.value.onclose = () => {
    console.log('WebSocket连接已关闭')
  }
}

// 发送消息
const sendMessage = () => {
  if (!userInput.value.trim()) return

  // 添加用户消息
  messages.push({
    role: 'user',
    content: userInput.value,
    isActive: false
  })

  // 通过WebSocket发送消息
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.send(JSON.stringify({
      content: userInput.value
    }))
  }

  // 清空输入框
  userInput.value = ''

  // 自动滚动到底部
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 组件挂载时初始化WebSocket
onMounted(() => {
  initSocket()
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (socket.value) {
    socket.value.close()
  }
})
</script>

<style scoped>
.chat-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.chat-container {
  width: 100%;
  max-width: 500px;
  height: 700px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 20px;
  text-align: center;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 5px;
}

.header-subtitle {
  font-size: 14px;
  opacity: 0.8;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  background-color: #f9fafb;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
}

.user-message {
  flex-direction: row-reverse; /* 用户消息头像在右侧 */
}

.ai-message {
  flex-direction: row; /* AI消息头像在左侧 */
}

.message-avatar {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e9ecef;
  border-radius: 50%;
  flex-shrink: 0;
}

.user-avatar {
  background-color: #e6f3ff;
}

.ai-avatar {
  background-color: #f1f3f5;
}

.message-content {
  max-width: calc(100% - 60px); /* 减去头像和间距的宽度 */
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.5;
  position: relative;
}

.user-message .message-content {
  background-color: #e6f3ff;
  margin-left: 10px;
  color: #2c3e50;
}

.ai-message .message-content {
  background-color: #f1f3f5;
  margin-right: 10px;
  color: #2c3e50;
}

.chat-input-container {
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e9ecef;
}

.chat-input {
  display: flex;
  align-items: center;
  background-color: #f1f3f5;
  border-radius: 30px;
  overflow: hidden;
}

.chat-input input {
  flex-grow: 1;
  padding: 12px 15px;
  border: none;
  background: transparent;
  font-size: 16px;
  outline: none; /* 移除输入框的默认聚焦边框 */
}

.chat-input input:focus {
  outline: none; /* 再次确保聚焦时没有黑边 */
  box-shadow: none;
}

.send-button {
  background-color: #2575fc;
  color: white;
  border: none;
  width: 45px;
  border: none;
  height: 45px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background-color: #1a5aff;
}

.cursor {
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f3f5;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #6a11cb;
  border-radius: 3px;
}
</style>